import {
	baseURL
} from './config.js'
export const request = (opts) => {
	let reveal = opts.reveal || false // 返回code为0 当作接口正常不提示报错
	let data = opts.data || {}
	const query = opts.query || false
	let url = baseURL + opts.url
	let params = {}
	for (let key in data) {
		params[key] = data[key]
	}
	if (query) { //把参数拼接在接口请求后面
		let parameter = Object.keys(query).map(key => key + "=" + query[key]).join("&");
		url = `${url}?${parameter}`
	}
	let defaultOpts = {
		header: opts.header ? {
			...opts.header,
			'Authorization': uni.getStorageSync('App-Token') || ''
		} : {
			//#ifdef APP-PLUS
			'type': 1,
			//#endif
			'Content-type': 'application/json',
			'Authorization': uni.getStorageSync('App-Token') || ''
		},
		url,
		method: opts.method || 'GET',
		dataType: opts.dataType || 'json',
		data: params
	}
	let promise = new Promise(function(resolve, reject) {
		// #ifdef MP-WEIXIN
		// uni.showNavigationBarLoading()
		// #endif		
		// defaultOpts.data.count = 'false'
		uni.request(defaultOpts)
			.then((response) => {
				uni.stopPullDownRefresh()
				uni.hideNavigationBarLoading()
				// setTimeout(() => {
					// uni.hideNavigationBarLoading()
				// }, 500)
				if (response[1].data.code == 200) {
					if (response[1].header.Authorization) {
						uni.setStorageSync('App-Token', response[1].header.Authorization)
					}
					resolve(response[1].data)
				} else if (response[1].data.code == 200 && reveal) {
					if (response[1].header.Authorization) {
						uni.setStorageSync('App-Token', response[1].header.Authorization)
					}
					resolve(response[1].data)
				} else if (response[1].data.code == 401) {
					// uni.clearStorageSync();
					// uni.showToast({
					// 	icon: 'none',
					// 	title: '请登录',
					// 	duration: 2000
					// });
					uni.removeStorageSync('token');
					uni.removeStorageSync('userInfo');
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						})
						// uni.navigateTo({
						// 	url: '/pages/login/index'
						// })
					}, 100)
				} else {
					if (response[1].data.msg) {
						uni.showToast({
							icon: 'none',
							title: response[1].data.msg,
							duration: 2000
						});
					}
				}

			})
			.catch((error) => {
				// reject(error)
				uni.showToast({
					icon: 'none',
					title: '网络错误,请稍后重试!',
					duration: 2000
				});
			})
	})

	return promise
}
